import 'dart:convert';

import 'package:inmotion_pro/service/db_tables/db_realtime_data.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'db_tables/db_table_user.dart';
import 'db_tables/db_table_vehicle.dart';
import 'db_tables/db_tables.dart';

// 数据库服务
class UserService extends GetxService {
  // 数据库服务
  static UserService get to => Get.find();

  // 数据库
  Database? _database;

  // 数据库文件名
  static const _databaseName = 'app_users_vehicles.db';

  // 获取数据库实例（懒加载）
  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDatabase();
    return _database!;
  }

  // 初始化数据库
  Future<Database> _initDatabase() async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, _databaseName);
    debugPrint('数据库路径: $path');
    return openDatabase(
      path,
      version: 1,
      onCreate: (db, version) async {
        // 创建用户表
        await db.execute('''
          CREATE TABLE IF NOT EXISTS ${DbTables.users} (
            ${DbTables.id} INTEGER PRIMARY KEY AUTOINCREMENT,
            ${DbTableUserKeys.userId} INTEGER UNIQUE NOT NULL,
            ${DbTableUserKeys.token} TEXT NOT NULL,
            ${DbTableUserKeys.xAuth} TEXT NOT NULL,
            ${DbTableUserKeys.timezoneOffset} INTEGER,
            ${DbTableUserKeys.signature} TEXT ,
            ${DbTableUserKeys.coin} INTEGER,
            ${DbTableUserKeys.country} TEXT,
            ${DbTableUserKeys.province} TEXT,
            ${DbTableUserKeys.city} TEXT,
            ${DbTableUserKeys.name} TEXT,
            ${DbTableUserKeys.nickname} TEXT,
            ${DbTableUserKeys.birthday} TEXT,
            ${DbTableUserKeys.avatar} TEXT,
            ${DbTableUserKeys.email} TEXT,
            ${DbTableUserKeys.phone} TEXT,
            ${DbTableUserKeys.checkinContinuedDays} INTEGER,
            ${DbTableUserKeys.sex} INTEGER,
            ${DbTableUserKeys.isSelected} INTEGER DEFAULT 0
          )
        ''');

        // 创建车辆表（关联用户userId）
        await db.execute('''
          CREATE TABLE IF NOT EXISTS ${DbTables.vehicles} (
            ${DbTables.id} INTEGER PRIMARY KEY AUTOINCREMENT,
            ${DbTableVehicleKeys.userId} INTEGER NOT NULL,
            ${DbTableVehicleKeys.bleName} TEXT UNIQUE NOT NULL,
            ${DbTableVehicleKeys.productModel} TEXT,
            ${DbTableVehicleKeys.sn} TEXT,
            ${DbTableVehicleKeys.createdStamp} INTEGER DEFAULT 0,
            ${DbTableVehicleKeys.updatedStamp} INTEGER DEFAULT 0,
            ${DbTableVehicleKeys.connectStamp} INTEGER DEFAULT 0,
            ${DbTableVehicleKeys.vehicleName} TEXT,
            ${DbTableVehicleKeys.isSelected} INTEGER DEFAULT 0,
            ${DbTableVehicleKeys.firmwareInfo} TEXT,
            ${DbTableVehicleKeys.realtimeLocationSwitch} INTEGER DEFAULT 0,
            ${DbTableVehicleKeys.isOwner} INTEGER DEFAULT 0,
            ${DbTableVehicleKeys.hmicStatus} INTEGER DEFAULT 0,
            ${DbTableVehicleKeys.tboxStatus} INTEGER DEFAULT -1,

            FOREIGN KEY (${DbTableVehicleKeys.userId}) 
              REFERENCES ${DbTables.users} (${DbTableUserKeys.userId})
              ON DELETE CASCADE
          )
        ''');

        // 创建实时数据表（关联车辆bleName）
        await db.execute('''
          CREATE TABLE IF NOT EXISTS ${DbTables.realtimeData} (
            ${DbTables.id} INTEGER PRIMARY KEY AUTOINCREMENT,
            ${DbTableVehicleKeys.userId} INTEGER NOT NULL,
            ${DbTableVehicleKeys.bleName} TEXT NOT NULL,
            ${DbTableVehicleKeys.sn} TEXT,
            ${DbTableRealtimeDataKeys.estimatedRemainingMileage} REAL,
            ${DbTableRealtimeDataKeys.totalMileage} REAL,
            ${DbTableRealtimeDataKeys.batteryPercent} REAL,
            ${DbTableRealtimeDataKeys.itemList} TEXT,
            ${DbTableRealtimeDataKeys.cyclingRecord} TEXT,
            FOREIGN KEY (${DbTableVehicleKeys.bleName}) 
              REFERENCES ${DbTables.vehicles} (${DbTableVehicleKeys.bleName})
              ON DELETE CASCADE,
            FOREIGN KEY (${DbTableVehicleKeys.userId}) 
              REFERENCES ${DbTables.users} (${DbTableUserKeys.userId})
              ON DELETE CASCADE
          )
        ''');
      },
      onConfigure: (db) async {
        // 启用外键约束
        await db.execute('PRAGMA foreign_keys = ON');
        // 验证是否生效
        final result = await db.rawQuery('PRAGMA foreign_keys');
        debugPrint('外键约束已启用');
        assert(result.first['foreign_keys'] == 1, '外键约束未启用');
      },
    );
  }

  // 查询数据库
  Future<List<Map<String, dynamic>>> query(
    String table, {
    bool? distinct,
    List<String>? columns,
    String? where,
    List<Object?>? whereArgs,
    String? groupBy,
    String? having,
    String? orderBy,
    int? limit,
    int? offset,
  }) async {
    final db = await database;
    final result = await db.query(
      table,
      distinct: distinct,
      columns: columns,
      where: where,
      whereArgs: whereArgs,
      groupBy: groupBy,
      having: having,
      orderBy: orderBy,
      limit: limit,
      offset: offset,
    );
    debugPrint('查询结果: $result');
    return result;
  }

  // 重置数据库（测试用）
  Future<void> resetTestDatabase() async {
    // 使用测试专用的数据库路径
    final testDbPath = join(await getDatabasesPath(), _databaseName);
    // 删除现有数据库
    try {
      await deleteDatabase(testDbPath);
    } catch (e) {
      debugPrint('删除测试数据库失败: $e');
    }
    // 初始化新数据库
    final db = await openDatabase(testDbPath);
    await db.close();
  }

  // MARK: - 构建User Map对象
  Map<String, dynamic> buildUserMap({
    required int userId,
    required String token,
    required String xAuth,
    required int timezoneOffset,
    String? signature,
    int? coin,
    String? country,
    String? province,
    String? city,
    String? name,
    String? nickname,
    String? birthday,
    String? avatar,
    String? email,
    String? phone,
    int? checkinContinuedDays,
    int? sex,
    bool isSelected = false,
  }) {
    return {
      DbTableUserKeys.userId: userId,
      DbTableUserKeys.token: token,
      DbTableUserKeys.xAuth: xAuth,
      DbTableUserKeys.timezoneOffset: timezoneOffset,
      DbTableUserKeys.isSelected: isSelected ? 1 : 0, // 0: false, 1: true
      if (signature != null) DbTableUserKeys.signature: signature,
      if (coin != null) DbTableUserKeys.coin: coin,
      if (country != null) DbTableUserKeys.country: country,
      if (province != null) DbTableUserKeys.province: province,
      if (city != null) DbTableUserKeys.city: city,
      if (name != null) DbTableUserKeys.name: name,
      if (nickname != null) DbTableUserKeys.nickname: nickname,
      if (birthday != null) DbTableUserKeys.birthday: birthday,
      if (avatar != null) DbTableUserKeys.avatar: avatar,
      if (email != null) DbTableUserKeys.email: email,
      if (phone != null) DbTableUserKeys.phone: phone,
      if (checkinContinuedDays != null)
        DbTableUserKeys.checkinContinuedDays: checkinContinuedDays,
      if (sex != null) DbTableUserKeys.sex: sex,
    };
  }

  // MARK: - 增加用户
  Future<bool> newUser(Map<String, dynamic> user) async {
    final db = await database;
    final userId = user[DbTableUserKeys.userId];

    // 先查询用户是否存在
    if (await getUserById(userId) != null) {
      // 用户存在，执行更新
      return db.update(
        DbTables.users,
        _fitlerUserMap(user),
        where: '${DbTableUserKeys.userId} = ?',
        whereArgs: [userId],
      ).then((value) => value > 0);
    } else {
      // 用户不存在，执行插入
      return db
          .insert(DbTables.users, _fitlerUserMap(user),
              conflictAlgorithm: ConflictAlgorithm.replace)
          .then((value) => value > 0);
    }
  }

  // MARK: - 过滤User Map对象
  Map<String, dynamic> _fitlerUserMap(Map<String, dynamic> user) {
    return {
      DbTableUserKeys.userId: user[DbTableUserKeys.userId],
      DbTableUserKeys.email: user[DbTableUserKeys.email],
      DbTableUserKeys.token: user[DbTableUserKeys.token],
      DbTableUserKeys.isSelected: user[DbTableUserKeys.isSelected],
      DbTableUserKeys.xAuth: user[DbTableUserKeys.xAuth],
      if (user[DbTableUserKeys.name] != null)
        DbTableUserKeys.name: user[DbTableUserKeys.name],
      if (user[DbTableUserKeys.nickname] != null)
        DbTableUserKeys.nickname: user[DbTableUserKeys.nickname],
      if (user[DbTableUserKeys.phone] != null)
        DbTableUserKeys.phone: user[DbTableUserKeys.phone],
      if (user[DbTableUserKeys.avatar] != null)
        DbTableUserKeys.avatar: user[DbTableUserKeys.avatar],
      if (user[DbTableUserKeys.signature] != null)
        DbTableUserKeys.signature: user[DbTableUserKeys.signature],
      if (user[DbTableUserKeys.timezoneOffset] != null)
        DbTableUserKeys.timezoneOffset: user[DbTableUserKeys.timezoneOffset],
      if (user[DbTableUserKeys.coin] != null)
        DbTableUserKeys.coin: user[DbTableUserKeys.coin],
      if (user[DbTableUserKeys.country] != null)
        DbTableUserKeys.country: user[DbTableUserKeys.country],
      if (user[DbTableUserKeys.province] != null)
        DbTableUserKeys.province: user[DbTableUserKeys.province],
      if (user[DbTableUserKeys.city] != null)
        DbTableUserKeys.city: user[DbTableUserKeys.city],
      if (user[DbTableUserKeys.birthday] != null)
        DbTableUserKeys.birthday: user[DbTableUserKeys.birthday],
      if (user[DbTableUserKeys.checkinContinuedDays] != null)
        DbTableUserKeys.checkinContinuedDays:
            user[DbTableUserKeys.checkinContinuedDays],
      if (user[DbTableUserKeys.sex] != null)
        DbTableUserKeys.sex: user[DbTableUserKeys.sex],
    };
  }

  // MARK: - 删除用户（级联删除关联车辆）
  Future<bool> cacheMixinDeleteUser(int userId) {
    return database
        .then((db) => db.delete(
              DbTables.users,
              where: '${DbTableUserKeys.userId} = ?',
              whereArgs: [userId],
            ))
        .then((val) => Future(() => val > 0));
  }

  // MARK: - 更新用户
  Future<bool> updateUser(
    int userId, {
    String? email,
    String? token,
    String? xAuth,
    String? name,
    String? nickName,
    String? phone,
    String? avatar,
    String? signature,
    bool? isSelected,
  }) {
    Map<String, dynamic> map = {};
    if (token != null) map[DbTableUserKeys.token] = token;
    if (xAuth != null) map[DbTableUserKeys.xAuth] = xAuth;
    if (name != null) map[DbTableUserKeys.name] = name;
    if (nickName != null) map[DbTableUserKeys.nickname] = nickName;
    if (phone != null) map[DbTableUserKeys.phone] = phone;
    if (avatar != null) map[DbTableUserKeys.avatar] = avatar;
    if (email != null) map[DbTableUserKeys.email] = email;
    if (signature != null) map[DbTableUserKeys.signature] = signature;
    if (isSelected != null) {
      map[DbTableUserKeys.isSelected] =
          isSelected == true ? 1 : 0; // 0: false, 1: true
    }
    // 串行之行更新
    return map.entries.fold(
      Future(() => true),
      (prev, entry) => prev.then((val) {
        if (val) {
          return database
              .then((db) => db.update(
                    DbTables.users,
                    {entry.key: entry.value},
                    where: '${DbTableUserKeys.userId} = ?',
                    whereArgs: [userId],
                  ))
              .then((val) => Future(() => val > 0));
        } else {
          return Future(() => false);
        }
      }),
    );
  }

  // MARK: - 获取用户
  Future<Map<String, dynamic>?> getUserById(int userId) async {
    final db = await database;
    final result = await db.query(
      DbTables.users,
      where: '${DbTableUserKeys.userId} = ?',
      whereArgs: [userId],
      limit: 1,
    );
    return result.isNotEmpty ? result.first : null;
  }

  // MARK: - 获取所有用户
  Future<List<Map<String, dynamic>>> getAllUsers() async {
    final db = await database;
    return db.query(DbTables.users);
  }

  // MARK: - 构建Vehicle Map
  Map<String, dynamic> buildVehicleMap({
    required String bleName,
    String? vehicleName,
    String? sn,
    String? productModel,
    int? createdStamp,
    int? updatedStamp,
    int? connectStamp,
    bool? isSelected,
    String? firmwareInfo,
    bool? isOwner,
    int? tboxStatus,
    int? hmicStatus,
  }) {
    return {
      DbTableVehicleKeys.bleName: bleName,
      if (productModel != null) DbTableVehicleKeys.productModel: productModel,
      if (createdStamp != null) DbTableVehicleKeys.createdStamp: createdStamp,
      if (updatedStamp != null) DbTableVehicleKeys.updatedStamp: updatedStamp,
      if (connectStamp != null) DbTableVehicleKeys.connectStamp: connectStamp,
      if (sn != null) DbTableVehicleKeys.sn: sn,
      if (vehicleName != null) DbTableVehicleKeys.vehicleName: vehicleName,
      if (isSelected != null)
        DbTableVehicleKeys.isSelected: isSelected == true ? 1 : 0,
      if (firmwareInfo != null) DbTableVehicleKeys.firmwareInfo: firmwareInfo,
      if (isOwner != null) DbTableVehicleKeys.isOwner: isOwner == true ? 1 : 0,
      if (tboxStatus != null) DbTableVehicleKeys.tboxStatus: tboxStatus,
      if (hmicStatus != null) DbTableVehicleKeys.hmicStatus: hmicStatus,
    };
  }

  // MARK: - 新增车辆 [userId 指定用户下]
  Future<bool> newVehicle(Map<String, dynamic> data, int userId) async {
    final vehicle = _fitlerVehicleMap(data);
    if (await getUserById(userId) == null) {
      // 用户不存在
      return Future(() => false);
    } else {
      vehicle[DbTableVehicleKeys.userId] = userId;
      // 用户存在
      if (await getVehicleByBleName(
              userId, vehicle[DbTableVehicleKeys.bleName]) !=
          null) {
        // 车辆已存在，则更新
        final vehicleCopy = Map<String, dynamic>.from(vehicle);
        return database
            .then((db) => db.update(
                  DbTables.vehicles,
                  vehicleCopy,
                  where: '${DbTableVehicleKeys.bleName} = ?',
                  whereArgs: [vehicleCopy[DbTableVehicleKeys.bleName]],
                ))
            .then((val) => Future(() => val > 0));
      } else {
        // 车辆不存在，则插入
        return database
            .then(
              (db) => db.insert(
                DbTables.vehicles,
                vehicle,
                conflictAlgorithm: ConflictAlgorithm.replace,
              ),
            )
            .then((val) => Future(() => val > 0));
      }
    }
  }

  // MARK: - 过滤User Map对象
  Map<String, dynamic> _fitlerVehicleMap(Map<String, dynamic> vehicle) {
    return {
      DbTableVehicleKeys.userId: vehicle[DbTableVehicleKeys.userId],
      DbTableVehicleKeys.bleName: vehicle[DbTableVehicleKeys.bleName],
      DbTableVehicleKeys.productModel: vehicle[DbTableVehicleKeys.productModel],
      if (vehicle[DbTableVehicleKeys.sn] != null)
        DbTableVehicleKeys.sn: vehicle[DbTableVehicleKeys.sn],
      if (vehicle[DbTableVehicleKeys.createdStamp] != null)
        DbTableVehicleKeys.createdStamp:
            vehicle[DbTableVehicleKeys.createdStamp],
      if (vehicle[DbTableVehicleKeys.updatedStamp] != null)
        DbTableVehicleKeys.updatedStamp:
            vehicle[DbTableVehicleKeys.updatedStamp],
      if (vehicle[DbTableVehicleKeys.connectStamp] != null)
        DbTableVehicleKeys.connectStamp:
            vehicle[DbTableVehicleKeys.connectStamp],
      if (vehicle[DbTableVehicleKeys.vehicleName] != null)
        DbTableVehicleKeys.vehicleName: vehicle[DbTableVehicleKeys.vehicleName],
      if (vehicle[DbTableVehicleKeys.isSelected] != null)
        DbTableVehicleKeys.isSelected: vehicle[DbTableVehicleKeys.isSelected],
      if (vehicle[DbTableVehicleKeys.firmwareInfo] != null)
        DbTableVehicleKeys.firmwareInfo:
            vehicle[DbTableVehicleKeys.firmwareInfo],
      if (vehicle[DbTableVehicleKeys.realtimeLocationSwitch] != null)
        DbTableVehicleKeys.realtimeLocationSwitch:
            vehicle[DbTableVehicleKeys.realtimeLocationSwitch],
      if (vehicle[DbTableVehicleKeys.isOwner] != null)
        DbTableVehicleKeys.isOwner: vehicle[DbTableVehicleKeys.isOwner],
      if (vehicle[DbTableVehicleKeys.tboxStatus] != null)
        DbTableVehicleKeys.tboxStatus: vehicle[DbTableVehicleKeys.tboxStatus],
      if (vehicle[DbTableVehicleKeys.hmicStatus] != null)
        DbTableVehicleKeys.hmicStatus: vehicle[DbTableVehicleKeys.hmicStatus],
    };
  }

  // MARK: - 删除指定用户的车辆
  Future<bool> deleteVehicle(
    int userId,
    String bleName,
  ) async {
    return database
        .then((db) => db.delete(
              DbTables.vehicles,
              where:
                  '${DbTableVehicleKeys.userId} = ? AND ${DbTableVehicleKeys.bleName} = ?',
              whereArgs: [userId, bleName],
            ))
        .then((val) => Future(() => val > 0));
  }

  // MARK: - 更新车辆
  Future<bool> updateVehicle({
    required int userId,
    required String bleName,
    String? productModel,
    int? createdStamp,
    int? updatedStamp,
    int? connectStamp,
    String? vehicleName,
    String? sn,
    bool? isSelected,
    String? firmwareInfo,
    bool? isOwner,
    int? tboxStatus,
    int? hmicStatus,
  }) {
    Map<String, dynamic> map = {};
    map[DbTableVehicleKeys.userId] = userId;
    map[DbTableVehicleKeys.bleName] = bleName;
    if (productModel != null) {
      map[DbTableVehicleKeys.productModel] = productModel;
    }
    if (createdStamp != null) {
      map[DbTableVehicleKeys.createdStamp] = createdStamp;
    }
    if (updatedStamp != null) {
      map[DbTableVehicleKeys.updatedStamp] = updatedStamp;
    }
    if (connectStamp != null) {
      map[DbTableVehicleKeys.connectStamp] = connectStamp;
    }
    if (vehicleName != null) {
      map[DbTableVehicleKeys.vehicleName] = vehicleName;
    }
    if (sn != null) {
      map[DbTableVehicleKeys.sn] = sn;
    }
    if (isSelected != null) {
      map[DbTableVehicleKeys.isSelected] = isSelected == true ? 1 : 0;
    }
    if (firmwareInfo != null) {
      map[DbTableVehicleKeys.firmwareInfo] = firmwareInfo;
    }
    if (isOwner != null) {
      map[DbTableVehicleKeys.isOwner] = isOwner == true ? 1 : 0;
    }
    if (tboxStatus != null) {
      map[DbTableVehicleKeys.tboxStatus] = tboxStatus;
    }
    if (hmicStatus != null) {
      map[DbTableVehicleKeys.hmicStatus] = hmicStatus;
    }
    // 串行执行更新
    return map.entries.fold(
      Future(() => true),
      (prev, entry) => prev.then((val) {
        if (val) {
          return database
              .then((db) => db.update(
                    DbTables.vehicles,
                    {entry.key: entry.value},
                    where:
                        '${DbTableVehicleKeys.userId} = ? AND ${DbTableVehicleKeys.bleName} = ?',
                    whereArgs: [userId, bleName],
                  ))
              .then((val) => Future(() => val > 0));
        } else {
          return Future(() => false);
        }
      }),
    );
  }

  // MARK: - 获取车辆
  Future<Map<String, dynamic>?> getVehicleByBleName(
      int userId, String bleName) async {
    Database db = await database;
    List<Map<String, dynamic>> result = await db.query(
      DbTables.vehicles,
      where:
          '${DbTableVehicleKeys.userId} = ? AND ${DbTableVehicleKeys.bleName} = ?',
      whereArgs: [userId, bleName],
      limit: 1,
    );
    return result.isNotEmpty ? result.first : null;
  }

  // MARK: - 获取用户的所有车辆
  Future<List<Map<String, dynamic>>> getVehicles(int userId) async {
    final db = await database;
    return db.query(
      DbTables.vehicles,
      where: '${DbTableVehicleKeys.userId} = ?',
      whereArgs: [userId],
    );
  }

  // MARK: - 构建RealtimeData Map对象
  Map<String, dynamic> buildRealtimeDataMap(
    int userId,
    String bleName,
    List<Map<String, dynamic>> realtimeItems, {
    String? sn,
    double? estimatedRemainingMileage, // 预估剩余里程
    double? totalMileage,
    double? batteryPercent,
  }) {
    return {
      DbTableVehicleKeys.userId: userId,
      DbTableVehicleKeys.bleName: bleName,
      DbTableRealtimeDataKeys.itemList: jsonEncode(realtimeItems),
      if (sn != null) DbTableVehicleKeys.sn: sn,
      if (estimatedRemainingMileage != null)
        DbTableRealtimeDataKeys.estimatedRemainingMileage:
            estimatedRemainingMileage,
      if (totalMileage != null)
        DbTableRealtimeDataKeys.totalMileage: totalMileage,
      if (batteryPercent != null)
        DbTableRealtimeDataKeys.batteryPercent: batteryPercent,
    };
  }

  // MARK: - 新增车辆实时数据
  Future<bool> newVehicleRealtimeDataByBleName(
    int userId,
    String bleName,
    List<Map<String, dynamic>> realtimeItems, {
    String? sn,
    double? estimatedRemainingMileage, // 预估剩余里程
    double? totalMileage,
    double? batteryPercent,
    Map<String, dynamic>? cyclingRecord,
  }) async {
    Map<String, dynamic> data = {};
    data[DbTableVehicleKeys.userId] = userId;
    data[DbTableVehicleKeys.bleName] = bleName;
    data[DbTableRealtimeDataKeys.itemList] = jsonEncode(realtimeItems);
    if (sn != null) {
      data[DbTableVehicleKeys.sn] = sn;
    }
    if (estimatedRemainingMileage != null) {
      data[DbTableRealtimeDataKeys.estimatedRemainingMileage] =
          estimatedRemainingMileage;
    }
    if (totalMileage != null) {
      data[DbTableRealtimeDataKeys.totalMileage] = totalMileage;
    }
    if (batteryPercent != null) {
      data[DbTableRealtimeDataKeys.batteryPercent] = batteryPercent;
    }
    if (cyclingRecord != null) {
      data[DbTableRealtimeDataKeys.cyclingRecord] = jsonEncode(cyclingRecord);
    }
    // 判断车辆是否存在
    if (await getVehicleByBleName(userId, bleName) == null) {
      // 车辆不存在
      return Future(() => false);
    } else {
      // 判断车辆实时数据是否存在
      if (await getRealtimeDataByBleName(userId, bleName) != null) {
        // 存在则更新
        return database
            .then((db) => db.update(
                  DbTables.realtimeData,
                  data,
                  where:
                      '${DbTableVehicleKeys.userId} = ? AND ${DbTableVehicleKeys.bleName} = ?',
                  whereArgs: [userId, bleName],
                ))
            .then((val) => Future(() => val > 0));
      } else {
        // 不存在则插入
        return database
            .then(
              (db) => db.insert(
                DbTables.realtimeData,
                data,
                conflictAlgorithm: ConflictAlgorithm.replace,
              ),
            )
            .then((val) => Future(() => val > 0));
      }
    }
  }

  // MARK: - 更新车辆实时数据
  Future<bool> updateVehicleRealtimeDataByBleName(
    int userId,
    String bleName,
    List<Map<String, dynamic>> realtimeItems, {
    double? estimatedRemainingMileage, // 预估剩余里程
    double? totalMileage,
    double? batteryPercent,
    Map<String, dynamic>? cyclingRecord,
  }) {
    Map<String, dynamic> map = {};
    map[DbTableRealtimeDataKeys.itemList] = jsonEncode(realtimeItems);
    if (estimatedRemainingMileage != null) {
      map[DbTableRealtimeDataKeys.estimatedRemainingMileage] =
          estimatedRemainingMileage;
    }
    if (totalMileage != null) {
      map[DbTableRealtimeDataKeys.totalMileage] = totalMileage;
    }
    if (batteryPercent != null) {
      map[DbTableRealtimeDataKeys.batteryPercent] = batteryPercent;
    }
    if (cyclingRecord != null) {
      map[DbTableRealtimeDataKeys.cyclingRecord] = jsonEncode(cyclingRecord);
    }
    // 串行执行更新
    return map.entries.fold(
      Future(() => true),
      (prev, entry) => prev.then((val) {
        if (val) {
          return database
              .then((db) => db.update(
                    DbTables.realtimeData,
                    {entry.key: entry.value},
                    where:
                        '${DbTableVehicleKeys.userId} = ? AND ${DbTableVehicleKeys.bleName} = ?',
                    whereArgs: [userId, bleName],
                  ))
              .then((val) => Future(() => val > 0));
        } else {
          return Future(() => false);
        }
      }),
    );
  }

  // MARK: - 获取车辆实时数据
  Future<Map<String, dynamic>?> getRealtimeDataByBleName(
    int userId,
    String bleName,
  ) async {
    final db = await database;
    final result = await db.query(
      DbTables.realtimeData,
      where:
          '${DbTableVehicleKeys.userId} = ? AND ${DbTableVehicleKeys.bleName} = ?',
      whereArgs: [userId, bleName],
      limit: 1,
    );
    return result.isNotEmpty ? result.first : null;
  }
}
